package org.budo.ocr.service.baidu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.budo.ocr.service.api.OcrRequest;
import org.budo.ocr.service.api.OcrResponse;
import org.budo.ocr.service.impl.DefaultOcrResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.aip.ocr.AipOcr;

/**
 * @author limingwei
 */
public class BaiduAiOcrService extends AbstractBaiduAiOcrService {
    private static final Logger log = LoggerFactory.getLogger(BaiduAiOcrService.class);

    @Override
    public OcrResponse recognition(OcrRequest request) {
        AipOcr client = this.getAipOcr();

        JSONObject responseJson = client.basicGeneral(request.getByteArray(), new HashMap<String, String>());

        if (null == responseJson.opt("words_result")) {
            log.error("#30 no words_result, responseJson=" + responseJson);
            return null;
        }

        JSONArray wordsResult = responseJson.getJSONArray("words_result");
        if (null == wordsResult || wordsResult.length() < 1) {
            log.error("#28 wordsResult=" + wordsResult + ", responseJson=" + responseJson);
            return null;
        }

        List<String> words = new ArrayList<String>();
        for (Object each : wordsResult) {
            JSONObject json = (JSONObject) each;
            words.add(json.getString("words"));
        }

        DefaultOcrResponse response = new DefaultOcrResponse(words);
        log.info("#41 request=" + request + ", response=" + response);
        return response;
    }
}